import { _decorator, Component, Node, SkeletalAnimationComponent } from "cc";
import MapNavAgent from "../AStar/MapNavAgent";
import { EventMgr } from "../Managers/EventMgr";
const { ccclass, property } = _decorator;

export var EnmeyState = {
    Idle: 0,
    Run: 1,
    Attack: 2,
    Dead: 3,
}

@ccclass("EnemyCtrl")
export class EnemyCtrl extends Component {
    private state: number = -1;
    private anim: SkeletalAnimationComponent = null;
    private nav: MapNavAgent = null;

    private hp: number = 0; // 我们从配置表里面读取的;
    private config: any = null;

    onLoad(): void {
        this.nav = this.node.addComponent(MapNavAgent);
        this.anim = this.node.getComponentInChildren(SkeletalAnimationComponent);
    }

    public initEnemyConfig(config): void {
        this.config = config;
        this.hp = config.hp;
        this.nav.InitMapNavAgent(config.speed);
    }

    public onAttacked(killValue): void {
        if (this.state > EnmeyState.Run) {
            return;
        }

        this.hp -= killValue;
        if (this.hp <= 0) { // 人被干死了;
            this.setState(EnmeyState.Dead);
        }
    }

    public setState(state): void {
        if (state === this.state) { // 一定要判断,如果不断，state === 想通;
            return;
        }


        this.state = state;
        this.anim.stop(); // 引擎有个小bug, stop;

        switch(this.state) {
            case EnmeyState.Idle:
                this.anim.crossFade("idle"); // 平滑过渡, 切换动画，都掉这个;
            break;
            case EnmeyState.Run:
                this.nav.NavOnRoadWithFirst(this.config.roadData, function() {
                    this.setState(EnmeyState.Attack);
                }.bind(this));
                this.anim.crossFade("run"); // 平滑过渡, 切换动画，都掉这个;
            break;
            case EnmeyState.Attack:
                this.anim.crossFade("attack"); // 平滑过渡, 切换动画，都掉这个;
                EventMgr.Instance.dispatch_event("AttackPlayer", this.config.killValue);
                this.scheduleOnce(function() {
                    this.node.removeFromParent();
                }.bind(this), 0.75);

            break;
            case EnmeyState.Dead:
                this.nav.StopNav();
                this.anim.crossFade("die"); // 平滑过渡, 切换动画，都掉这个;
                this.scheduleOnce(function() {
                    this.node.removeFromParent();
                }.bind(this), 1.79);
            break;
        }
    }
}
